package com.mce.nebula.controller;

import com.mce.nebula.dto.ApiResponse;
import com.mce.nebula.entity.Enterprise;
import com.mce.nebula.entity.User;
import com.mce.nebula.security.UserDetailsImpl;
import com.mce.nebula.service.EnterpriseService;
import com.mce.nebula.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 企业管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/enterprise")
@Tag(name = "企业管理", description = "企业管理相关接口")
@RequiredArgsConstructor
public class EnterpriseController {
    
    private final EnterpriseService enterpriseService;
    private final UserService userService;
    
    @GetMapping("/{enterpriseId}")
    @Operation(summary = "获取企业信息", description = "获取指定企业的详细信息")
    public ResponseEntity<ApiResponse<Enterprise>> getEnterprise(@PathVariable String enterpriseId) {
        try {
            Optional<Enterprise> enterprise = enterpriseService.getEnterpriseById(enterpriseId);
            return enterprise.map(value -> ResponseEntity.ok(ApiResponse.success(value))).orElseGet(() -> ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "企业不存在")));
        } catch (Exception e) {
            log.error("Failed to get enterprise: {}", enterpriseId, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
//    @GetMapping("/{enterpriseId}/overview")
//    @Operation(summary = "企业总览", description = "获取企业总览信息")
//    public ResponseEntity<ApiResponse<Map<String, Object>>> getEnterpriseOverview(@PathVariable String enterpriseId) {
//        try {
//            Map<String, Object> overview = enterpriseService.get(enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(overview));
//        } catch (Exception e) {
//            log.error("Failed to get enterprise overview: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
    @GetMapping("/{enterpriseId}/users")
    @Operation(summary = "获取企业用户", description = "获取企业下的所有用户")
    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
    public ResponseEntity<ApiResponse<List<User>>> getEnterpriseUsers(
            @PathVariable String enterpriseId,
            @RequestParam(required = false) String query,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<User> users = this.userService.getEnterpriseUsers(enterpriseId);
            return ResponseEntity.ok(ApiResponse.success(users));
        } catch (Exception e) {
            log.error("Failed to get enterprise users: {}", enterpriseId, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @PostMapping("/{enterpriseId}/users")
    @Operation(summary = "添加企业用户", description = "添加新用户到企业")
    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
    public ResponseEntity<ApiResponse<User>> addEnterpriseUser(
            @PathVariable String enterpriseId,
            @RequestBody User userData) {
        try {
            User user = this.userService.createUser(userData.getNickName(), userData.getEmail(), userData.getPassword(),enterpriseId);
            return ResponseEntity.ok(ApiResponse.success(user, "用户添加成功"));
        } catch (Exception e) {
            log.error("Failed to add enterprise user: {}", enterpriseId, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @PutMapping("/{enterpriseId}/users/{userId}")
    @Operation(summary = "更新企业用户", description = "更新企业用户信息")
    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
    public ResponseEntity<ApiResponse<List<User>>> updateEnterpriseUser(
            @PathVariable String enterpriseId,
            @PathVariable Integer userId,
            @RequestBody Map<String, Object> userData) {
        try {
            List<User> users = this.userService.getEnterpriseUsers(enterpriseId);
            return ResponseEntity.ok(ApiResponse.success(users, "用户更新成功"));
        } catch (Exception e) {
            log.error("Failed to update enterprise user: {} in enterprise: {}", userId, enterpriseId, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
    @DeleteMapping("/{enterpriseId}/users/{userId}")
    @Operation(summary = "删除企业用户", description = "从企业中删除用户")
    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
    public ResponseEntity<ApiResponse<Void>> deleteEnterpriseUser(
            @PathVariable String enterpriseId,
            @PathVariable Integer userId) {
        try {
            // todo 删除用户
//            enterpriseService.deleteEnterpriseUser(enterpriseId, userId);
            return ResponseEntity.ok(ApiResponse.success(null, "用户删除成功"));
        } catch (Exception e) {
            log.error("Failed to delete enterprise user: {} from enterprise: {}", userId, enterpriseId, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }
    
//    @GetMapping("/{enterpriseId}/teams")
//    @Operation(summary = "获取企业团队", description = "获取企业下的所有团队")
//    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getEnterpriseTeams(@PathVariable String enterpriseId) {
//        try {
//            List<Map<String, Object>> teams = enterpriseService.getEnterpriseTeams(enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(teams));
//        } catch (Exception e) {
//            log.error("Failed to get enterprise teams: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @GetMapping("/{enterpriseId}/regions")
//    @Operation(summary = "获取企业数据中心", description = "获取企业下的所有数据中心")
//    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getEnterpriseRegions(@PathVariable String enterpriseId) {
//        try {
//            List<Map<String, Object>> regions = enterpriseService.getEnterpriseRegions(enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(regions));
//        } catch (Exception e) {
//            log.error("Failed to get enterprise regions: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @GetMapping("/{enterpriseId}/configs")
//    @Operation(summary = "获取企业配置", description = "获取企业配置信息")
//    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Map<String, Object>>> getEnterpriseConfigs(@PathVariable String enterpriseId) {
//        try {
//            Map<String, Object> configs = enterpriseService.getEnterpriseConfigs(enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(configs));
//        } catch (Exception e) {
//            log.error("Failed to get enterprise configs: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @PutMapping("/{enterpriseId}/configs")
//    @Operation(summary = "更新企业配置", description = "更新企业配置信息")
//    @PreAuthorize("hasRole('ADMIN') or @enterpriseService.isEnterpriseAdmin(#enterpriseId, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> updateEnterpriseConfigs(
//            @PathVariable String enterpriseId,
//            @RequestBody Map<String, Object> configs) {
//        try {
//            enterpriseService.updateEnterpriseConfigs(enterpriseId, configs);
//            return ResponseEntity.ok(ApiResponse.success(null, "配置更新成功"));
//        } catch (Exception e) {
//            log.error("Failed to update enterprise configs: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
    
//    @GetMapping("/{enterpriseId}/monitor")
//    @Operation(summary = "企业监控", description = "获取企业监控信息")
//    public ResponseEntity<ApiResponse<Map<String, Object>>> getEnterpriseMonitor(@PathVariable String enterpriseId) {
//        try {
//            Map<String, Object> monitor = enterpriseService.getEnterpriseMonitor(enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(monitor));
//        } catch (Exception e) {
//            log.error("Failed to get enterprise monitor: {}", enterpriseId, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
}



